package com.whut.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whut.mapper.*;
import com.whut.model.*;
import com.whut.service.MeasureService;
import com.whut.utils.FormatDate;
import com.whut.utils.RangeHelper;
import com.whut.v_model.MeasureQualifiedRateItem;
import com.whut.v_model.MeasureResultData;
import com.whut.v_model.MeasureTableDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.List;

/***
* 实测实量模块ServiceImpl
* @author fuzhenjie
* @date 19.8.9 20:26
*/
@Service("measureService")
public class MeasureServiceImpl implements MeasureService {


    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MeasureServiceImpl.class);


    @Resource
    private MeasuresystemMapper measuresystemMapper;
    @Resource
    private MeasureresulttypeMapper measureresulttypeMapper;
    @Resource
    private MeasureTableDetailMapper measureTableDetailMapper;
    @Resource
    private MeasuretablerecordMapper measuretablerecordMapper;
    @Resource
    private MeasureresultMapper measureresultMapper;
    @Resource
    private ContractchecktaskMapper contractchecktaskMapper;

    private static final String SUCCESS = "success";
    private static final String ERROR = "error";

    @Override
    public Object insertSystem(Measuresystem measureSystem) {
        JSONObject jsonObject = new JSONObject();
        try {
            measuresystemMapper.insert(measureSystem);
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measuresystem> list = measuresystemMapper.getSameFloorList(measureSystem.getPreNum());
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public Object getSystemByPreNum(int preNum) {
        return measuresystemMapper.getSameFloorList(preNum);
    }

    @Override
    public Object updateSystem(Measuresystem measureSystem) {
        JSONObject jsonObject = new JSONObject();
        try {
            measuresystemMapper.updateByPrimaryKey(measureSystem);
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measuresystem> list = measuresystemMapper.getSameFloorList(measureSystem.getPreNum());
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public Object getResultTypeList(int preNum) {
        return measureresulttypeMapper.getByPreNum(preNum);
    }

    @Override
    public Object insertResultType(Measureresulttype measureResultType) {
        JSONObject jsonObject = new JSONObject();
        String result = RangeHelper.isRangeStringValid(measureResultType.getRangeMath());
        if(!"correct".equals(result)){
            jsonObject.put("operationCode",ERROR);
            jsonObject.put("message",result);
            List<Measureresulttype> list = measureresulttypeMapper.getByPreNum(measureResultType.getPreNum());
            jsonObject.put("updateData",list);
            return jsonObject;
        }
        try {
            measureresulttypeMapper.insert(measureResultType);
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measureresulttype> list = measureresulttypeMapper.getByPreNum(measureResultType.getPreNum());
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public Object updateResultType(Measureresulttype measureResultType) {
        JSONObject jsonObject = new JSONObject();
        String result = RangeHelper.isRangeStringValid(measureResultType.getRangeMath());
        if(!"correct".equals(result)){
            jsonObject.put("operationCode",ERROR);
            jsonObject.put("message",result);
            List<Measureresulttype> list = measureresulttypeMapper.getByPreNum(measureResultType.getPreNum());
            jsonObject.put("updateData",list);
            return jsonObject;
        }
        try {
            measureresulttypeMapper.updateByPrimaryKey(measureResultType);
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measureresulttype> list = measureresulttypeMapper.getByPreNum(measureResultType.getPreNum());
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public Object delResultType(Measureresulttype measureresulttype) {
        int fatherKey = measureresulttype.getPreNum();
        JSONObject jsonObject = new JSONObject();
        try {
            measureresulttypeMapper.deleteByPrimaryKey(measureresulttype.getmKey());
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measureresulttype> list = measureresulttypeMapper.getByPreNum(fatherKey);
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public Object delSystem(Measuresystem measuresystem) {
        int fatherKey = measuresystem.getPreNum();
        JSONObject jsonObject = new JSONObject();
        try {
            measuresystemMapper.deleteByPrimaryKey(measuresystem.getmKey());
            jsonObject.put("operationCode",SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("operationCode",ERROR);
        }finally {
            //再次查找同级的数据同前置节点的数据
            List<Measuresystem> list = measuresystemMapper.getSameFloorList(fatherKey);
            jsonObject.put("updateData",list);
        }
        return jsonObject;
    }

    @Override
    public List<MeasureTableDetail> getTableDetailByTableId(int tableId) {
        return measureTableDetailMapper.selectAllByTableId(tableId);
    }

    @Transactional(rollbackFor = SQLException.class)
    @Override
    public Object insertResultData(ContractCheckTask cct, String jsonString,int userId) {
        //LOGGER.error(JSON.toJSONString(cct));
        //LOGGER.error(jsonString);
        JSONObject res = new JSONObject();

        //得到数据
        JSONArray jsonArray = JSONArray.parseArray(jsonString);

        //1 先新建一条记录
        Measuretablerecord measuretablerecord = new Measuretablerecord();
        measuretablerecord.setUserId(userId);
        JSONObject jsonObject0 = jsonArray.getJSONObject(0);
        measuretablerecord.setMeasureTableName(jsonObject0.getString("parameterName4"));
        measuretablerecord.setMeasureTableId(jsonObject0.getIntValue("sysId4"));
        measuretablerecord = initialMeasureTableRecord(measuretablerecord,cct);

        Measuresystem m4 = measuresystemMapper.selectByPrimaryKey(jsonObject0.getIntValue("sysId4"));
        Measuresystem m3 = measuresystemMapper.selectByPrimaryKey(m4.getPreNum());
        // 设置第三级 名字
        measuretablerecord.setReserve2(m3.getParameterName());


        measuretablerecordMapper.insert(measuretablerecord);

        int tableRecordId = measuretablerecord.getmKey();

        //存储 各项的合格点数以计算总的合格点数
        int qualifiedCount = 0,totalCount = 0;
        String rangeNameSum = "";


        for(int i = 0;i<jsonArray.size();i++){//每一种结果类型
            JSONObject item = jsonArray.getJSONObject(i);
            Measureresult measureresult = new Measureresult();
            measureresult.setRecordId(tableRecordId);
            measureresult.setResultTypeId(item.getInteger("rtId"));
            measureresult.setType(item.getByte("type"));
            measureresult.setCheckPart("无");

            if(!item.getBoolean("fill")){
                measureresult.setIsEmpty(true);
                measureresultMapper.insert(measureresult);
                continue;
            }else{
                rangeNameSum = rangeNameSum + item.getString("rangeName") + " ";
                measureresult.setIsEmpty(false);
                measureresult.setCheckPart(item.getString("checkPart"));
                String rangeMath = item.getString("rangeMath");
                String data = item.getString("pointData");
                MeasureResultData measureResultData = JSON.parseObject(data,MeasureResultData.class);
                String rate = "";
                JSONObject rateJSON;
                switch (measureresult.getType()){
                    case 0:
                        rateJSON = measureResultData.generateRate(rangeMath);
                        rate = rateJSON.getString("singleRate");
                        qualifiedCount+=rateJSON.getInteger("qualifiedPointsNum");
                        totalCount+=rateJSON.getInteger("totalPointsNum");
                        break;
                    case 1:
                        rateJSON = measureResultData.generateRateType1(rangeMath);
                        rate = rateJSON.getString("singleRate");
                        qualifiedCount+=rateJSON.getInteger("qualifiedPointsNum");
                        totalCount+=rateJSON.getInteger("totalPointsNum");
                        break;
                    case 2:
                        rateJSON = measureResultData.generateRateType2(rangeMath);
                        rate = rateJSON.getString("singleRate");
                        qualifiedCount+=rateJSON.getInteger("qualifiedPointsNum");
                        totalCount+=rateJSON.getInteger("totalPointsNum");
                        break;
                    default:

                }
                measureresult.setQualifiedRate(rate);
                measureResultData.setCheckPart(measureresult.getCheckPart());
                measureresult.setPointData(JSON.toJSONString(measureResultData));

                measureresultMapper.insert(measureresult);
            }
        }

        double totalRate = (double)qualifiedCount/totalCount;
        String totalQualifiedRate = new DecimalFormat("#.##%").format(totalRate);
        measuretablerecord.setTotalQualifiedRate(totalQualifiedRate);
        measuretablerecord.setTotalPointNumber(totalCount);
        measuretablerecord.setQualifiedPointNumber(qualifiedCount);
        //写入备注的和
        measuretablerecord.setReserve1(rangeNameSum);
        measuretablerecordMapper.updateByPrimaryKey(measuretablerecord);

        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String data = jsonObject.getString("pointData");

        MeasureResultData measureResultData =  JSON.parseObject(data,MeasureResultData.class);

        //LOGGER.error(measureResultData.getDesignValue()+"");
        res.put("msg",SUCCESS);
        res.put("rate",totalQualifiedRate);
        return res;
    }

    /**
     * LYL
     * @param checkId
     * @return
     */
    @Override
    public List<Measuretablerecord> getTableData(int checkId) {
        return measuretablerecordMapper.getTableData(checkId);
    }

    /**
     * 初始化一条记录
     * @param measuretablerecord 记录
     * @param cct 参数来源
     * @return 返回此条记录
     */
    private Measuretablerecord initialMeasureTableRecord(Measuretablerecord measuretablerecord, ContractCheckTask cct) {
        measuretablerecord.setCheckId(cct.getCheckId());
        measuretablerecord.setCheckName(cct.getCheckName());
        measuretablerecord.setContractId(cct.getContractId());
        //measuretablerecord.setFinishTime(cct.getFinishTime());
        measuretablerecord.setFinishTime(FormatDate.getDateStringYMD());
        measuretablerecord.setProjectId(cct.getProjectId());
        measuretablerecord.setProjectName(cct.getProjectName());
        measuretablerecord.setTaskId(cct.getTaskId());
        measuretablerecord.setTestUnit("湖北毅瑞");
        return measuretablerecord;
    }

    @Override
    public JSONObject getRecordRateDetail(int recordId) {
        Measuretablerecord measuretablerecord = measuretablerecordMapper.selectByPrimaryKey(recordId);
        List<MeasureQualifiedRateItem> list = measureresultMapper.getRateShowItem(recordId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("record",measuretablerecord);
        jsonObject.put("children",list);
        return jsonObject;
    }



    @Override
    public Object getCctListByUserId(int userId,int curPage,int pageSize) {
        PageHelper.startPage(curPage,pageSize);
        List<ContractCheckTask> list = contractchecktaskMapper.getCctListByUserId(userId);
        PageInfo result = new PageInfo(list);
        return result;
    }


    @Override
    public List<Measuretablerecord> getMeasureDetailByCct(int mKey) {
        return measuretablerecordMapper.getMeasureDetailByCct(mKey);
    }

    @Override
    public Object getnewTableData(int checkId) {
        return measuretablerecordMapper.getnewTableData(checkId);
    }
}
